# -*- coding: UTF-8 -*-
#coding=utf-8
import TravelDir
from PIL import Image
import os
'''
    1、如果只设置width,height同比例拉伸，不会导致变形
    2、同理只设置height
    3、如果width、height都设置，那么直接按照这个比例将图片调整
'''
def resize_image(img_path, new_width=None, new_height=None):
    try:
        img = Image.open(img_path)
        (width,height) = img.size
        if new_width!=None and new_height!=None:
            pass
        else:
            if new_height == None:
                new_height = new_width*height/width
            if new_width == None:
                new_width = new_height*width/height
        
        out = img.resize((new_width,new_height),Image.ANTIALIAS)
        file_dirname = os.path.dirname(img_path)+"/bak/"
        if os.path.exists(file_dirname) == False:
            os.mkdir(file_dirname)
        new_file_name = file_dirname+os.path.basename(img_path)
        out.save(new_file_name,quality=95)
    except Exception,e:
        print e
if __name__ == '__main__':
    resize_image('./picture.jpg',100,200)